#include "organizerwidget.h"
#include "gridwidget.h"

OrganizerWidget::OrganizerWidget()
{
    createWidgets();
    createMenu();
    setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Expanding);
    currentDir = ActualDataModel::getRoot();
    currentTag = "";
}

QSize OrganizerWidget::sizeHint() const
{
    return QSize(window()->width() * 0.30, window()->height());
}

void OrganizerWidget::createMenu()
{
    contextMenu = new QMenu();
    add = new QAction(tr("add"),this);
    edit = new QAction(tr("edit"),this);
    del = new QAction(tr("delete"),this);

    addFolder = new QAction(tr("add folder"),this);
    renameFolder = new QAction(tr("rename folder"),this);
    delFolder = new QAction(tr("delete folder"),this);

    contextMenu->addAction(add);
    contextMenu->addAction(edit);
    contextMenu->addAction(del);
    contextMenu->addSeparator();
    contextMenu->addAction(addFolder);
    contextMenu->addAction(renameFolder);
    contextMenu->addAction(delFolder);

}

void OrganizerWidget::createWidgets()
{
    QVBoxLayout* lay = new QVBoxLayout(this);
    lay->setContentsMargins(0,0,0,0);
    tabWidget = new QTabWidget(this);
    treeView = new QTreeWidget();
    tagView = new QListWidget();

    tabWidget->insertTab(0,treeView,"Folders");
    tabWidget->insertTab(1,tagView,"Tags");
    tabWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    ActualDataModel dataModel = ActualDataModel::getInstance();
    dummyData data = dummyData::getInstance(); //to populate
    QTreeWidgetItem* root = dataModel.getRoot();

    //treeView stuff
    treeView->setColumnCount(3);
    const QStringList headerLabels = (QStringList() << "Name" << "Tags" << "Address");
    treeView->setHeaderLabels(headerLabels);
    treeView->setColumnWidth(0,200);
    treeView->insertTopLevelItem(0, root);
    root->setExpanded(true);
    treeView->setSortingEnabled(true);
    treeView->setContextMenuPolicy(Qt::CustomContextMenu); 
    treeView->setAlternatingRowColors(true);
    treeView->setStyleSheet("QTreeView {alternate-background-color: #DEEEFF; margin:5px;}"
                            "QTreeView::item:hover {"
                            "background-color: #DDDDFF;"
                            "border: 1px solid #bfcde4;"
                            "}"
                            );

    //tagView stuff
    tagView->addItems(dataModel.taglist);
    tagView->setSortingEnabled(true);
    tagView->setAlternatingRowColors(true);
    tagView->setStyleSheet("QListView {alternate-background-color: #DEEEFF;margin:5px;}"
                           "QListView::item:hover {"
                           "background-color: #DDDDFF;"
                           "border: 1px solid #bfcde4;"
                           "}"
                           );

    lay->addWidget(tabWidget);
    this->setLayout(lay);

    connect(tagView,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(tagActivated(QListWidgetItem*)));
    connect(treeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(handleContextMenu(QPoint)));
    connect(treeView,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(itemIsSelected(QTreeWidgetItem*,int)));
    connect(tabWidget,SIGNAL(currentChanged(int)),this,SLOT(tabChanged(int)));
    connect(treeView,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(itemIsDoubleClicked(QTreeWidgetItem*,int)));
}

void OrganizerWidget::tabChanged(int n)
{
    GridWidget::getInstance()->removeAllWidgets();
    if(n==0)
    {
        if(currentDir)
            itemIsSelected(currentDir,0);
    }
    else
    {
        tagView->clear();
        tagView->addItems(ActualDataModel::getInstance().taglist);
        if(ActualDataModel::getInstance().taglist.contains(currentTag))
        {
            QString tag = currentTag;
            QList<QTreeWidgetItem*> setToDisplay = ActualDataModel::inOrderTraversal(tag,TAG,ActualDataModel::contains);
            GridWidget::getInstance()->displayList(setToDisplay);
        }
        else
        {
            if(tagView->count()>0)
            {
                tagView->item(0)->setSelected(true);
                currentTag = tagView->item(0)->text();
                GridWidget::getInstance()->setNoWidgets(0);
            }
        }
    }
}

void OrganizerWidget::tagActivated(QListWidgetItem *item)
{
    if(GridWidget::getInstance()->getSelected())
        GridWidget::getInstance()->getSelected()->setSelected(false);
    currentTag = item->text();
    QString tag = item->text();
    QList<QTreeWidgetItem*> setToDisplay = ActualDataModel::inOrderTraversal(tag,TAG,ActualDataModel::contains);
    GridWidget::getInstance()->displayList(setToDisplay);
    currentDir = ActualDataModel::getRoot();
}

void OrganizerWidget::refreshWidget()
{
    tabChanged((tabWidget->currentIndex()+1)%2);
}

void OrganizerWidget::itemIsSelected(QTreeWidgetItem *item, int column)
{
    if(GridWidget::getInstance()->getSelected())
        GridWidget::getInstance()->getSelected()->setSelected(false);
    int nChildren = item->childCount();
    QList<QTreeWidgetItem*> setToDisplay;
    if(nChildren>0)
    {
        printf("%d\n",item->childCount());
        for(int i=0; i<nChildren; i++)
        {
            if(item->child(i)->text(TYPE) == BOOKMARKSTR)
            setToDisplay << item->child(i);

        }
        GridWidget::getInstance()->displayList(setToDisplay);
        currentDir = item;
    }
}

void OrganizerWidget::itemIsDoubleClicked(QTreeWidgetItem *item, int col)
{
    qDebug()<< "weeee";
    if(item->text(TYPE) == BOOKMARKSTR)
    {
        QProcess *p = new QProcess();
        p->start(settingsDialog::getInstance()->getDefaultBrowserPath(),QStringList() << item->text(ADDR));
    }
}

void OrganizerWidget::handleContextMenu(const QPoint& pt)
{
    if(treeView->selectedItems().count() == 0) return;
    QPoint globalPos = this->mapToGlobal(pt);
    QAction* act = contextMenu->exec(globalPos);
    QList<QTreeWidgetItem *> items = treeView->selectedItems();
    QTreeWidgetItem* firstItem = items.at(0);
    if(act == add)
    {
        if(firstItem->text(TYPE) == FOLDERSTR) //folder
        {
            EditDialog* e = new EditDialog();
            connect(e,SIGNAL(accepted()), this, SLOT(addItem()));
            e->show();
        }
    }
    else if(act == edit)
    {
        if(firstItem->text(TYPE) == BOOKMARKSTR) //folder
        {
            EditDialog* e = new EditDialog();
            e->setName(firstItem->text(NAME));
            e->setTags(firstItem->data(TAG,Qt::UserRole).toStringList());
            e->setAddress(firstItem->text(ADDR));

            connect(e,SIGNAL(accepted()), this, SLOT(editItem()));

            e->show();
        }
    }
    else if(act == del)
    {
        deleteItem();
    }
    else if(act == addFolder)
    {
        addAFolder();
    }
    else if(act == renameFolder)
    {
        renameAFolder();
    }
    else if(act == delFolder)
    {
        deleteAFolder();
    }

}

void OrganizerWidget::addItem()
{
    EditDialog* e = (EditDialog*)sender();
    QTreeWidgetItem* newchild;

    if(treeView->selectedItems().count()>0)
    {
        QPixmap p = e->getThumbs();
        QString thumbpath = QString(":/images/youtube.jpg");
        if(!p.isNull())
        {
            thumbpath = e->getName() + ".png";
            p.save(thumbpath);
        }
        else
        {
            qDebug()<<"NO!";
        }
        newchild = ActualDataModel::add(treeView->selectedItems().at(0),e->getName(),e->getTags(),e->getAddress(),thumbpath,BOOKMARK);
        treeView->selectedItems().at(0)->setExpanded(true);
        treeView->selectedItems().at(0)->setSelected(false);
        newchild->setSelected(true);
        GridWidget::getInstance()->show();
    }
    tagView->clear();
    tagView->addItems(ActualDataModel::getInstance().taglist);
    delete e;
}

void OrganizerWidget::deleteItem()
{
    if(treeView->selectedItems().count()>0)
    {
        ActualDataModel::remove(treeView->selectedItems().at(0));
        GridWidget::getInstance()->removeAllWidgets();
    }
    tagView->clear();
    tagView->addItems(ActualDataModel::getInstance().taglist);
 }

void OrganizerWidget::editItem()
{
    EditDialog* e = (EditDialog*)sender();

    if(treeView->selectedItems().count()>0)
    {
        QPixmap p = e->getThumbs();
        QString thumbpath = treeView->selectedItems().at(0)->text(THUMB);
        if(!p.isNull())
        {
            thumbpath = e->getName() + ".png";
            p.save(thumbpath);
        }
        ActualDataModel::edit(treeView->selectedItems().at(0),e->getName(),e->getTags(),e->getAddress(),thumbpath);
        itemIsSelected(treeView->selectedItems().at(0)->parent(),0);
    }
    tagView->clear();
    tagView->addItems(ActualDataModel::getInstance().taglist);
    delete e;
}

void OrganizerWidget::addAFolder()
{
    //qDebug()<<"boo";
    QTreeWidgetItem* firstItem;
    if(treeView->selectedItems().count()>0)
        firstItem = treeView->selectedItems().at(0);
    else
        firstItem = ActualDataModel::getRoot();

    if(firstItem->text(TYPE) == FOLDERSTR)
    {
        QTreeWidgetItem* child = ActualDataModel::add(firstItem,QString("New Folder"),QStringList(),QString(),QString(),FOLDER);
        firstItem->setExpanded(true);
        child->setFlags(child->flags() | Qt::ItemIsEditable);
        treeView->editItem(child,0);
    }
}

void OrganizerWidget::renameAFolder()
{
    QTreeWidgetItem* firstItem;
    if(treeView->selectedItems().count()>0)
        firstItem = treeView->selectedItems().at(0);
    else
        return;

    if(firstItem->text(TYPE) == FOLDERSTR)
    {
        firstItem->setFlags(firstItem->flags() | Qt::ItemIsEditable);
        treeView->editItem(firstItem,0);
    }
}

void OrganizerWidget::deleteAFolder()
{
    QTreeWidgetItem* firstItem;
    if(treeView->selectedItems().count()>0)
        firstItem = treeView->selectedItems().at(0);
    else
        return;

    if(firstItem->text(TYPE) == FOLDERSTR)
    {
        ActualDataModel::remove(firstItem);
    }
}
